package ru.arriah.servicedesk.ejb.help;

import java.util.Date;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;


public class MailSender {

  private String charset;
  private String host;
  private String protocol;

  public MailSender() {
    setCharset("Windows-1251");
    setHost("mail.arriah.ru");
    setProtocol("smtp");
  }

  public MailSender(
      String charset, 
      String host,
      String protocol
  ) {
    setCharset(charset);
    setHost(host);
    setProtocol(protocol);
  }
  
  /**
   * 
   * @param toAddress
   * @param fromAddress
   * @param mailSubject
   * @param mailText
   * @param login
   * @param password
   * 
   * @author Osminin
   */
  public void sendMail(String toAddress, String fromAddress,
      String mailSubject, String mailText, String login, String password) {
    try {
      Properties mailProperties = new Properties();      
      mailProperties.put("mail.smtp.auth", "true");
      mailProperties.put("mail.transport.protocol", this.getProtocol());

      Session session = Session.getInstance(mailProperties);

      InternetAddress[] ia = InternetAddress.parse(toAddress);
      Transport transport = session.getTransport();

      MimeMessage message = new MimeMessage(session);
      
      message.setFrom(new InternetAddress(fromAddress));
      message.setSentDate(new Date());
      message.setRecipients(Message.RecipientType.TO, ia);
      message.setSubject(mailSubject);
      message.setText(mailText, this.getCharset());

      transport.connect(this.getHost(), 25, login, password);
      transport.sendMessage(message, ia);
      transport.close();
    } catch (Exception e) {
      e.printStackTrace();      
    }
  }

  public String getHost() {
    return this.host;
  }

  public void setHost(String host) {
    this.host = host;
  }
  
  public void setCharset(String charSet) {
    this.charset = charSet;
  }

  public String getCharset() {
    return this.charset;
  }
  
  public String getProtocol() {
    return this.protocol;
  }

  public void setProtocol(String protocol) {
    this.protocol = protocol;
  }
}